<template>
  <div class="terminal-page">
    <!-- 终端组件 -->
    <EnteringTerminal v-model="show" :conn="conn" :fullscreen="false" />
    
    <!-- 当终端未显示时的占位内容 -->
    <div v-if="!show" class="terminal-placeholder">
      <div class="placeholder-content">
        <h2>终端已关闭</h2>
        <p>终端连接已断开，正在返回主页面...</p>
        <div class="loading-spinner"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import EnteringTerminal from '@/components/Terminal/EnteringTerminal.vue'
import config from '@/config.js'
import { useTerminalStore } from '@/stores/terminalStore'
import { useRouter } from 'vue-router'

const show = ref(false)
const terminalStore = useTerminalStore()
const router = useRouter()
const conn = ref({
  host: config.terminal.host,
  username: config.terminal.username,
  password: config.terminal.password
})

// 页面加载时自动打开终端
onMounted(() => {
  // 检查全局状态中是否有终端连接状态
  if (terminalStore.isConnected) {
    conn.value = terminalStore.conn
  }

  // 延迟一小段时间确保组件完全加载
  setTimeout(() => {
    show.value = true
  }, 100)
  
  // 监听来自侧边栏的终端打开事件
  window.addEventListener('open-terminal', openTerminal)
})

onBeforeUnmount(() => {
  // 清理事件监听器
  window.removeEventListener('open-terminal', openTerminal)
})

function openTerminal() { 
  show.value = true 
}

// 监听终端关闭事件，提供备用导航逻辑
watch(show, (newValue) => {
  if (!newValue) {
    // 当终端关闭时，延迟导航到仪表板
    setTimeout(() => {
      router.push('/Dashboard/Analytics')
    }, 100)
  }
})

// 去除关闭后的回退逻辑，留在本页以便再次进入全屏
</script>

<style scoped>
.terminal-page {
  width: 100%;
  height: 100vh;
  position: relative;
}

.terminal-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  z-index: 1;
}

.placeholder-content {
  text-align: center;
  padding: 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 400px;
}

.placeholder-content h2 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.placeholder-content p {
  color: #666;
  margin-bottom: 1.5rem;
  line-height: 1.6;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .terminal-placeholder {
    background: #1a1a1a;
  }
  
  .placeholder-content {
    background: #2d2d30;
    color: #fff;
  }
  
  .placeholder-content h2 {
    color: #fff;
  }
  
  .placeholder-content p {
    color: #ccc;
  }
}
</style>

